package 二叉树层序遍历.填充每个节点的下一个右侧节点指针II;

import java.util.ArrayDeque;

public class Solution {
    public TreeNode connect(TreeNode root) {

        if (root == null)
            return null;

        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        TreeNode p, last = root;
        queue.offer(root);
        while (!queue.isEmpty()) {
            p = queue.poll();
            if (p.left != null) queue.offer(p.left);
            if (p.right != null) queue.offer(p.right);
            if (last == p) {
                p.next = null;
                last = queue.peekLast();
            }else{
                p.next = queue.peek();
            }
        }
        return root;
    }
}
